package com.explorati.aaTest;


public class ReverseLinkedList {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    //递归解法
    public ListNode reverse(ListNode head) {
        //如果为空，直接返回，如果next为空，直接返回
        //长度大于等于2，做反转
        //递归： reverse(head.next)，返回此节点后反转后的链表头 ListNodeNextReverse
        if(head == null) {
            return null;
        }
        if(head.next == null) {
            return head;
        }
        ListNode listNodeNextReverse = reverse(head.next);
        ListNode cur = listNodeNextReverse;
        while(cur.next != null) cur = cur.next;
        cur.next = head;
        head.next = null;
        return listNodeNextReverse;
    }

    //直接解法
    public ListNode reverse1(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

}
